/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.services.project;

import cn.easyplatform.dao.BizDao;
import cn.easyplatform.dao.DaoException;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.entities.beans.table.TableBean;
import cn.easyplatform.lang.Nums;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.vos.swift.TagOptionVo;
import cn.easyplatform.services.IBizService;
import cn.easyplatform.services.IProjectService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
class BizServiceImpl implements IBizService {

    private static final Logger log = LoggerFactory.getLogger(BizServiceImpl.class);

    private final static String CURRENCY_DECIMAL = "currency";

    private final static String SWIFT_TAGS = "swift";

    private IProjectService ps;

    //币别小数位档
    private Cache<Serializable, Integer> fractionDigitsMap;

    //swift tag信息档
    private Cache<Serializable, List<TagOptionVo>> swiftTags;

    BizServiceImpl(IProjectService ps) {
        this.ps = ps;
        fractionDigitsMap = ps.getCache(CURRENCY_DECIMAL);
        swiftTags = ps.getCache(SWIFT_TAGS);
        init();
    }


    private void init() {
        loadSwiftTags();
        loadDecimal();
    }

    private void loadSwiftTags() {
        TableBean tb = ps.getEntityHandler().getEntity("SWTAG");
        if (tb != null) {
            try {
                BizDao dao = ps.getBizDao(tb.getSubType());
                List<FieldDo[]> list = dao
                        .selectList(
                                "select MSG_TYPE,MAJOR,MINOR,MO_FLAG,SLASH_LINE1,SLASH_POS1,SLASH_LINE2,SLASH_POS2,WIDTH1,HEIGHT1,WIDTH2,HEIGHT2,TAGFORMAT1,MAJOR_DESP from "
                                        + tb.getId() + " order by MSG_TYPE",
                                null);
                String name = "";
                for (FieldDo[] data : list) {
                    String tagName = "MT" + data[0].getValue();
                    if (!name.equals(tagName)) {
                        name = tagName;
                        List<TagOptionVo> tags = new ArrayList<TagOptionVo>();
                        swiftTags.put(name, tags);
                    }
                    TagOptionVo tag = new TagOptionVo();
                    tag.setName(data[1].getValue() + ((String) data[2].getValue()).trim());
                    tag.setMoFlag(data[3].getValue() == null ? false : data[3]
                            .getValue().equals("M"));
                    tag.setSlashLine1(Nums.toInt(data[4].getValue(), 0));
                    tag.setSlashPos1(Nums.toInt(data[5].getValue(), 0));
                    tag.setSlashLine2(Nums.toInt(data[6].getValue(), 0));
                    tag.setSlashPos2(Nums.toInt(data[7].getValue(), 0));
                    tag.setWidth1(Nums.toInt(data[8].getValue(), 0));
                    tag.setHeight1(Nums.toInt(data[9].getValue(), 0));
                    tag.setWidth2(Nums.toInt(data[10].getValue(), 0));
                    tag.setHeight2(Nums.toInt(data[11].getValue(), 0));
                    tag.setFormat((String) data[12].getValue());
                    tag.setDescription((String) data[13].getValue());
                    swiftTags.get(name).add(tag);
                }
            } catch (DaoException e) {
                if (log.isWarnEnabled())
                    log.warn("Table '" + tb.getId() + "' does not exist.");
            }
        }
    }

    private void loadDecimal() {
        String accQuery = ps.getConfig().getAccQuery();
        if (!Strings.isBlank(accQuery)) {
            BizDao dao = null;
            if (accQuery.indexOf(":") > 0) {
                dao = ps.getBizDao(StringUtils.substringBefore(accQuery, ":"));
                accQuery = StringUtils.substringAfter(accQuery, ":");
            } else
                dao = ps.getBizDao();
            List<FieldDo[]> list = dao.selectList(accQuery, null);
            for (FieldDo[] data : list)
                fractionDigitsMap.put((String) data[0].getValue(), Nums.toInt(data[1].getValue(), 0));
        }
    }

    @Override
    public Integer getFractionDigits(String currency) {
        if (Strings.isBlank(currency) || fractionDigitsMap.size() == 0)
            return Currency.getInstance(ps.getLocale()).getDefaultFractionDigits();
        return fractionDigitsMap.get(currency);
    }

    @Override
    public List<TagOptionVo> getSwiftTags(String msgType) {
        return swiftTags.get(msgType);
    }

    @Override
    public void refresh(String type) {
        if ("SWTAG".equals(type)) {
            swiftTags.clear();
            loadSwiftTags();
        } else if ("ACC".equals(type)) {
            fractionDigitsMap.clear();
            loadDecimal();
        }
    }

    public void destory() {
        fractionDigitsMap.clear();
        swiftTags.clear();
        ps.removeCache(CURRENCY_DECIMAL);
        ps.removeCache(SWIFT_TAGS);
    }
}
